try: True, False
except NameError:
    (True, False) = (1, 0)

class JavaStringIO:
    # XXX IllegalAccessExceptions with StringBuffer?!? puhlease
    def __init__(self):
        ##    from java.lang import StringBuffer
        ##    self.buffer = StringBuffer()
        self.buffer = ''

    def write(self, string):
        # self.buffer.append(string)
        self.buffer += string
    def getvalue(self):
        # return self.buffer.toString()
        return self.buffer

def newStringBuffer():
    try: from StringIO import StringIO
    except ImportError:
        return JavaStringIO()

    return StringIO()

def _capture(function, *args, **kwd):
    buf = newStringBuffer()

    import sys
    stdout = sys.stdout
    stderr = sys.stderr

    sys.stdout = buf
    sys.stderr = buf

    try: value = function(*args, **kwd)
    except:
        value = None

        # Consider returning error state with output and flag,
        # instead of reraising..?

        sys.stdout = stdout
        sys.stderr = stderr

        (evalue, etype, tb) = sys.exc_info()
        raise evalue, etype, tb

    sys.stdout = stdout
    sys.stderr = stderr

    return (value, buf.getvalue())

def _count_lines(string):
    nr = 0
    ln = len(string)
    i = 0

    while i < ln:
        i = string.find('\n', i)
        if i < 0:
            break

        nr += 1
        i += 1

    return nr

def printTraceback():
    from sys import exc_info
    (etype, value, tb) = exc_info()

    print 'Traceback:'
    while tb:
        f = tb.tb_frame
        code = f.f_code
        print '  File "%s", line %d, in %s' % \
              (code.co_filename, f.f_lineno, code.co_name)

        tb = tb.tb_next

    print '%s: %s' % (etype, value)

def interact(ns_locals = None, ns_globals = None):
    if ns_locals is None:
        ns_locals = {}
    if ns_globals is None:
        ns_globals = globals()

    try:
        while True:
            line = raw_input('>>> ')

            try:
                code = compile(line, '<stdin>', 'single')
                result = eval(code, ns_locals, ns_globals)
                if result is not None:
                    print repr(result)

            except:
                printTraceback()

    except EOFError:
        print

class Options:
    def __init__(self, **kwd):
        self.__dict__.update(kwd)
        self.__args = []

    def __iadd__(self, arg):
        self.__args.append(arg)
        return self

    def __setitem__(self, name, value):
        name = str(name).strip().replace('-', '_')
        self.__dict__[name] = value

    def __str__(self):
        s = []
        for (name, value) in self.__dict__.items():
            s.append('%s: %s' % (name, value))

        s.append('-Positional:')
        for a in self.__args:
            s.append('  ' + a)

        return '\n'.join(s)

def parseCmdln(argv = None, **defaults):
    if argv is None:
        from sys import argv

    options = Options(**defaults)
    for arg in argv[1:]:
        if arg.startswith('--'):
            arg = arg[2:]
            if arg:
                arg = arg.split('=', 1)
                if len(arg) == 2:
                    (name, value) = arg
                    options[name] = value.strip()
                else:
                    (name,) = arg
                    options[name] = True

        elif arg.startswith('-'):
            pass
        else:
            options += arg

    return options

def old_examine(ns_locals, ns_globals):
    from code import InteractiveConsole as IC
    ns_locals['globs'] = ns_globals
    ic = IC(locals = ns_locals)
    ic.interact(banner = '')

COMMON_TOOLS_PATH = r'C:\Users\Clint\Documents\Projects\CommonTools\Packages'

def examine(ns_locals, ns_globals):
    import sys
    if not COMMON_TOOLS_PATH in sys.path:
        sys.path.append(COMMON_TOOLS_PATH)

    try: from my.interactive import ExamineEx
    except ImportError: return old_examine(ns_locals, ns_globals)
    else: return ExamineEx(ns_locals, ns_globals)

def getChatList():
    result = []
    for chat in skype.Skype.getAllChats():
        result.append('%-30s : (%-20s) : %s' % \
                      (chat.id, chat.status, chat.windowTitle))

    return '\n'.join(result)
